package com.web.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.jfinal.core.Controller;
import com.web.model.User;
import com.web.util.UUIDUtil;

/**
 * 
 * @author lifang
 * 增加注册功能，在注册成功之后再将发送激活邮件进行用户激活
 */
public class RegistController extends Controller{

	public void index()
	{
		render("/view/regist/regist.html");
	}
	
	/**
	 * 用户注册主方法
	 */
	public void save()
	{
		String email =  getPara("email");
		String username =  getPara("username");
		String password = getPara("password");
		String code ="";
		String check = User.dao.getUserByEmail(email);
		if(!check.equals(""))
		{
			renderText("该邮箱已经注册");
			render("/view/regist/regist.html");
			return;
		}
		//如果发送邮件失败，则返回到错误页面
		try {
			code = sendActivateEmail(email,username);
		} catch (MessagingException e) {
			//跳转到注册失败页面
			render("/view/regist/error.html");
			return;
		}
		//如果返回的激活码为空，则报错
		if(code.equals(""))
		{
			render("/view/regist/error.html");
			return;
		}
		else
		{
			boolean flag = new User().set("username", username).set("password", password).set("email", email)
			.set("active_code", code).save();
			if(!flag)
			{
				render("/view/regist/error.html");
				return;
			}
			else
			{
				render("/view/regist/active.html");
				return;
			}
		}
	}
	
	/**
	 * 密碼驗證內部類
	 * @author lenovo
	 *
	 */
	class MyAuthenticator extends Authenticator{   
	    String userName=null;   
	    String password=null;   
	        
	    public MyAuthenticator(){   
	    }   
	    public MyAuthenticator(String username, String password) {    
	        this.userName = username;    
	        this.password = password;    
	    }    
	    protected PasswordAuthentication getPasswordAuthentication(){   
	        return new PasswordAuthentication(userName, password);   
	    }   
	}   
	/**
	 * 发送验证邮件到用户注册邮箱
	 * @param email 用户的注册邮箱
	 * @return 随机邮件发送的四位的验证码
	 * @throws MessagingException 
	 */
	public String sendActivateEmail(String email,String username) throws MessagingException
	{
		String activate_code = "";
		Properties p  = new Properties();
		p.setProperty("mail.smtp.host", "smtp.163.com");
		p.setProperty("mail.smtp.port", "25");
		p.setProperty("mail.smtp.auth", "true");
		MyAuthenticator authentic = new MyAuthenticator("lifang722324@163.com", "1q2w3e4r!@#$");
		Session sendMailSession = Session.getDefaultInstance(p,authentic);  
		Message mailMessage = new MimeMessage(sendMailSession);   
		Address from = new InternetAddress("lifang722324@163.com");  
		mailMessage.setFrom(from); 
		Address to = new InternetAddress(email); 
		mailMessage.setRecipient(Message.RecipientType.TO,to);   
		mailMessage.setSubject("XX网站激活邮件");    
		mailMessage.setSentDate(new Date()); 
		activate_code = UUIDUtil.getUUID();
		System.out.println(activate_code);
		mailMessage.setText(createMsgTemplate(username, activate_code, email));   
		Transport.send(mailMessage);   
		return activate_code;
	}
	
	private String createMsgTemplate(String username,String active_code,String email)
	{
		StringBuffer sb = new StringBuffer();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		sb.append(username+",您好：");
		sb.append("\n");
		sb.append("\n");
		sb.append("感谢您注册xx网(www.XX.com)，点击下面的链接即可完成注册：");
		sb.append("\n");
		sb.append("\n");
		sb.append(getRequest().getRequestURL()+"/regist/active？username="+username+"&active_code="+active_code);
		sb.append("\n");
		sb.append("(如果链接无法点击，请将它拷贝到浏览器的地址栏中。)");
		sb.append("\n");
		sb.append("\n");
		sb.append("\n");
		sb.append("您的XX网账号为："+username);
		sb.append("\n");
		sb.append("\n");
		sb.append("\n");
		sb.append("XX网，感谢您的注册！");
		sb.append("\n");
		sb.append(df.format(new Date()));
		return sb.toString();
	}
	
	public static void main(String args[])
	{
		RegistController rc = new  RegistController();
		
		System.out.println(rc.createMsgTemplate("111", "222", "333"));
	}
}
